// pages/activity/group_exchange/group_info/group_info.js
var app = getApp();
var DateUtil = require('../../../../utils/DateUtil.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    remainTime: {
      hour: 0,
      min: 0,
      sec: 0,
      isBackHomeShow : false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.spell_group_id = options.spell_group_id;
    //生成分享码
    this.getShareToken();

    var pages = getCurrentPages();
    if (pages.length > 1) { //不显示
      this.isNotMainpage = true;
    } else {
      this.isNotMainpage = false;
    }
  },

  onShow: function() {
    //获取用户信息
    this.getMyInfo(() => {
      //获取开团信息
      this.getGroupDetail();
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var shareType;
    var path = '/pages/login/login?token=' + this.shareToken;
    return {
      title: this.myinfo.user_name + '喊你快来免费拼【' + this.data.group_info.ware.goods_name + '】>>',
      path: path,
      success: () => {
      }
    }
  },

  /**
   * 获取开团信息
   */
  getGroupDetail: function () {
    app.Ajax({
      url: '/api/index.php?app=group&act=detail',
      data: {
        spell_group_id: this.spell_group_id,
      },
      success: (res) => {
        // console.log(res)
        //计算拼团信息：空余席位、是否已经结束、是否是团长、是否已经参团、是否中奖
        /* 空余席位 */
        var empty = [];
        for (var i = 0; i < res.limit_numbers - res.join_numbers; i++) {
          empty.push(i);
        }
        res.empty = empty;
        /*是否已经结束 */
        res.is_end = res.ware.is_end;
        /* 是否是团长 */
        var is_creator = false;
        if (this.myinfo.user_id == res.creator_id) {
          is_creator = true;
        }
        res.is_creator = is_creator;
        /* 是否已经参团 */
        var is_joined = false;
        for (var i = 0; i < res.members.length; i++) {
          if (this.myinfo.user_id == res.members[i].member_user_id) {
            is_joined = true;
            break;
          }
        }
        res.is_joined = is_joined;
        /* 是否中奖 */
        var is_awarded = false;
        if (res.is_end == 1 && res.status == 3) { //已揭晓且中奖了
          is_awarded = true;
        }
        res.is_awarded = is_awarded;

        //设置参数
        this.setData({
          group_info: res,
        })
        // console.log(res)
        //如果还未成团并且还未到揭晓时间，进行倒计时
        if (res.is_end == 0 && res.status == 0) {
          var end_time = res.ware.end_time;
          end_time = end_time.replace(/-/g, "/");
          end_time = new Date(end_time);
          var now = new Date().getTime();
          var diffValue = end_time - now;
          var remainTime = parseInt(diffValue / 1000);
          this.groupTimeCountdown(remainTime);
        }
        //获取商品信息
        this.group_id = res.ware.goods_group_id;
        this.getGoodsOptions();
      }
    })
  },

  /**
   * 用户信息
   */
  getMyInfo: function (cb) {
    if (this.myinfo) {
      typeof cb == 'function' && cb();
      return;
    }

    app.getUserInfo((res) => {
      this.myinfo = res;
      typeof cb == 'function' && cb();
    })
  },

  /**
   * 生成分享码
   */
  getShareToken: function () {
    app.Ajax({
      method: 'POST',
      url: '/api/index.php?app=home&act=token',
      data: {
        type: 2,
        page: 'pages/activity/group_exchange/group_info/group_info?spell_group_id=' + this.spell_group_id,
        spell_group_id: this.spell_group_id
      },
      success: (res) => {
        this.shareToken = res.token;
      }
    })
  },

  /**
   * 组团倒计时
   */
  groupTimeCountdown: function (remainTime) {
    var self = this;
    timeCountdown(remainTime);
    var timeInterVal = setInterval(() => {
      timeCountdown(--remainTime);
      if (remainTime == 0) {
        clearInterval(timeInterVal);
      }
    }, 1000);
    function timeCountdown(remainTime) {
      var hour = parseInt(remainTime / 3600);
      var min = parseInt((remainTime - 3600 * hour) / 60) + '';
      if (min.length < 2) {
        min = '0' + min;
      }
      var sec = remainTime - 3600 * hour - 60 * min + '';
      if (sec.length < 2) {
        sec = '0' + sec;
      }
      var time = {
        hour: hour,
        min: min,
        sec: sec
      }
      self.setData({
        remainTime: time
      })
    }
  },

  /**
   * 免费拼团--商品
   */
  getGoodsOptions: function () {
    var goodsOption = {
      list_id: 'group_exchange',
      url: '/api/index.php?app=category&act=group_goods',
      data: {
        group_id: this.group_id,
        orderby: 'group_nums',
        order: 'desc',
        ex_goods_id: this.data.group_info.ware.goods_id
      }
    }
    this.setData({
      goodsOption: goodsOption,
      pageHeight: app.globalData.pageHeight - 2,
    })
  },

  /**
   * 加载更多商品
   */
  loadMoreGoods: function (e) {
    this.setData({
      goodsList: e.detail.data,
    })
  },

  /**
   * 查看商品信息
   */
  lookGoodsInfo: function (e) {
    var id = e.detail.id;
    wx.navigateTo({
      url: '../../../goods_detail/goods_detail?group_id=' + this.group_id + '&goods_id=' + id,
    })
  },

  /**
   * 参与拼团活动
   */
  joinGroup: function () {
    app.Ajax({
      url: '/api/index.php?app=group&act=join',
      method: 'POST',
      data: {
        spell_group_id: this.spell_group_id
      },
      success: (res) => {
        //重新获取拼团信息
        this.getGroupDetail();
      },
      fail: (err, code) => {
        this.code = code;
        if (code == 2) {
          this.messageToast({
            title: '参与失败',
            content: '你的星星余额不足，拼团失败',
            cancelText: '暂时放弃',
            confirmText: '做任务赚星星',
          }, 2);
        } else if (code == 1) {
          this.messageToast({
            title: '参与失败',
            content: '拼团人数已满，请参与其他拼团',
            cancelText: '暂时放弃',
            confirmText: '再开一团',
          }, 2);
        } else {
          this.messageToast(err);
        }
      }
    })
  },

  /**
   * 参与失败提示确认事件
   */
  confirmEvent: function() {
    if (this.code == 2) {
      wx.switchTab({
        url: '../../../task/task',
      })
    } else if (this.code == 1) {
      this.goGroupExchangePage();
    }
  },

  /**
   * 跳转到免费拼团首页
   */
  goGroupExchangePage: function () {
    wx.redirectTo({
      url: '../main_page/main_page?group_id=' + this.data.group_info.ware.goods_group_id,
    })
  },

  /**
   * 领取商品 
   */
  takeGoods: function () {
    wx.navigateTo({
      url: '../../../goods/receive_info/receive_info?order_id=' + this.data.group_info.my_group_order.order_id,
    })
  },

  /**
   * 查看订单 
   */
  checkOrderInfo: function () {
    wx.navigateTo({
      url: '../../../../pages/goods/exchanged_info/exchanged_info?order_id=' + this.data.group_info.my_group_order.order_id,
    })
  },
  
  /**
   * 消息提示
   */
  messageToast: function (param, toastType) {
    toastType = toastType || 0;
    if (toastType == 0) {
      this.setData({
        toastType: 0,
        message: param
      })
    } else if (toastType == 2) {
      this.setData({
        toastType: 2,
        modalOptions: param
      })
    }
  },

  /**
   * 监听列表滚动 
   */
  handleScroll: function(e){
    if (!this.isNotMainpage) {
      e.detail.distance > 166
        ?
        this.setData({
          isBackHomeShow: true
        })
        :
        this.setData({
          isBackHomeShow: false
        })
    }
  }
})